package com.sylar.happyreader;

import java.util.concurrent.Callable;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.sylar.happyreader.db.Crud;
import com.sylar.happyreader.listener.Callback;
import com.sylar.happyreader.net.HttpTool;
import com.sylar.happyreader.tools.Config;
import com.sylar.happyreader.tools.TaskUtils;
import com.sylar.happyreader.tools.Utils;
import com.sylar.happyreader.view.ColorChooserType;
import com.sylar.happyreader.view.UniversalColorView;

public class BookPagesActivity extends Activity implements Callable<String>, Callback<String>, OnClickListener {
	private ListView bookPageList;
//	private TextView titleText;
	private ImageView titleImage;
	private LinearLayout pageListLayout;
	
	private static final int MSG_READ_BOOKPAGELISTS = 400;
	public static final int MSG_GET_BOOK_DATA = 500;

	public static Crud dbCrud;
	private String sex;
	private String style;
	private String bookName;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_READ_BOOKPAGELISTS:
				Config.nowPage = (String) msg.obj;
				TaskUtils.doAsync(BookPagesActivity.this.getParent(), null, "数据加载中哦..", BookPagesActivity.this, BookPagesActivity.this);
				break;

			case MSG_GET_BOOK_DATA:
				if (Config.pagelists != null && Config.pagelists.length > 0) {
					bookPageList.setAdapter(new BookPageAdapter(Config.pagelists));
					bookPageList.setSelection(Config.pageNo);
				} else {
					BookPagesActivity.this.finish();
				}
				break;
			}

		};
	};

	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.bookpagelist);
//		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

		bookPageList = (ListView) findViewById(R.id.item_list);
//		titleText = (TextView) findViewById(R.id.titleText);
//		titleImage = (ImageView) findViewById(R.id.titleImage);
//		titleImage.setVisibility(View.GONE);
//		titleText.setVisibility(View.VISIBLE);
		
		bookName = this.getIntent().getStringExtra("bookName");
		style = this.getIntent().getStringExtra("style");
		sex = this.getIntent().getStringExtra("sex");
		
//		titleText.setText(bookName);

//		Button fontsizeBtn = (Button) findViewById(R.id.fontsizeBtn);
//		fontsizeBtn.setOnClickListener(this);
//
//		Button fontStyleBtn = (Button) findViewById(R.id.fontStyleBtn);
//		fontStyleBtn.setOnClickListener(this);
//
//		Button backgroundStyleBtn = (Button) findViewById(R.id.backgroundStyleBtn);
//		backgroundStyleBtn.setOnClickListener(this);
//
//		Button lightBtn = (Button) findViewById(R.id.lightBtn);
//		lightBtn.setOnClickListener(this);
		

		// Button isContinueBtn = (Button) findViewById(R.id.isContinueBtn);
		// isContinueBtn.setOnClickListener(this);

		LayoutInflater mInflater = LayoutInflater.from(this);
		View mViewheader = mInflater.inflate(R.layout.head, null);
		bookPageList.addHeaderView(mViewheader, null, false);


		if (dbCrud == null)
			dbCrud = new Crud(this);

		if (Config.pagelists != null && Config.pagelists.length > 0) {
			bookPageList.setAdapter(new BookPageAdapter(Config.pagelists));
			bookPageList.setSelection(Config.pageNo);
		} else {
			this.finish();
		}
		// if (!isContinueReadBook()) {
		// if (Config.pagelists != null && Config.pagelists.length > 0) {
		// bookPageList.setAdapter(new BookPageAdapter(Config.pagelists));
		// bookPageList.setSelection(Config.pageNo);
		// } else {
		// this.finish();
		// }
		// }

		bookPageList.setFastScrollEnabled(true);
		bookPageList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Config.pageNo = position - 1;
				Message msg = mHandler.obtainMessage(MSG_READ_BOOKPAGELISTS);
				msg.obj = Config.pagelists[Config.pageNo];
				mHandler.sendMessage(msg);
				
			}
		});
		
	}

	private boolean isContinueReadBook() {
		boolean b = false;
		boolean isContinue = Utils.getSettingsparamsByBoolean(this, "isContinue");
		if (isContinue) {
			int position = Utils.getSettingsparamsByInt(this, bookName);
			if (position > -1) {
				if (Config.pagelists != null && position < Config.pagelists.length) {
					Config.pageNo = position;
					Message msg = mHandler.obtainMessage(MSG_READ_BOOKPAGELISTS);
					msg.obj = Config.pagelists[position];
					mHandler.sendMessage(msg);
					b = true;
				}
			}
		}
		return b;
	}

	
	protected void onResume() {
		super.onResume();
		
//		MobclickAgent.onResume(this);
	}

	
	protected void onPause() {
		super.onPause();
//		finishTask();
//		MobclickAgent.onPause(this);
	}

	class BookPageAdapter extends BaseAdapter {
		String[] args;

		BookPageAdapter(String[] params) {
			this.args = params;
		}

		public int getCount() {
			return args.length;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			BookPageHolder holder;
			if (convertView == null) {
				convertView = BookPagesActivity.this.getLayoutInflater().inflate(R.layout.text_row, parent, false);
				holder = new BookPageHolder();
				holder.title = (TextView) convertView.findViewById(R.id.item_title);
				holder.msg = (TextView) convertView.findViewById(R.id.item_content);
				convertView.setTag(holder);
			} else {
				holder = (BookPageHolder) convertView.getTag();
			}
			holder.title.setText(args[position] + " 章");
			Boolean isExists = dbCrud.checkIsExists(bookName, args[position].trim());

			holder.msg.setText(isExists ? "已读" : "未读");

			return convertView;
		}

	}

	class BookPageHolder {
		public TextView title;
		public TextView msg;
	}

	
	public void onCallback(String pCallbackValue) {
		if (pCallbackValue != null && "ok".equals(pCallbackValue)) {
//			Intent intent = new Intent(this, ReadBookActivity.class);
			Intent intent = new Intent(this, ReadFilpBookActivity.class);
			intent.putExtra("style", style);
			intent.putExtra("sex", sex);
			intent.putExtra("bookName", bookName);
			this.startActivity(intent);
		} else if (pCallbackValue != null && "error".equals(pCallbackValue)) {
			Toast.makeText(this,"请求失败，请重试",0).show();
		}

	}

	
	public String call() throws Exception {
		String url = null;
		String result = null;
		url = Config.RequestUri + "sex=" + sex + "&style=" + Uri.encode(style) + "&bookName=" + Uri.encode(bookName) + "&pageCount="
				+ Uri.encode(Config.nowPage);
		String msg = HttpTool.getString(getApplicationContext(), url);
		if (msg != null ) {
			msg = msg.replace("光影之间团队分享", "");
			msg = msg.replace("更多精彩内容请访问", "");
			msg = msg.replace("http://www.newperl.com", "");
			ReadBookActivity.msg = msg;
			result = "ok";
		} else {
			result = "error";
		}

		return result;
	}

	
	protected void onDestroy() {
//		if (ad != null)
//			ad.destory();
		super.onDestroy();
	}

	private int mColor = -1;
	
	
	public void onClick(View v) {
		LayoutInflater factory = LayoutInflater.from(this);
		View mView = factory.inflate(R.layout.booksettingslist, null);
		ViewFlipper settingLayout = (ViewFlipper) mView.findViewById(R.id.settingLayout);

		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT);
		params.gravity=Gravity.CENTER;
		final TextView bookInfo = new TextView(this);
		bookInfo.setText("小说书城");
		bookInfo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		params.gravity = Gravity.CENTER;
		
		com.sylar.happyreader.view.OnColorChangedListener mColorChangedListener = new com.sylar.happyreader.view.OnColorChangedListener() {
			
			public void colorChanged(Object source, ColorChooserType type, int color) {
				bookInfo.setTextColor(color);
				mColor = color;
			}
		};
		
		switch (v.getId()) {
		case R.id.fontsizeBtn:
			settingLayout.setDisplayedChild(1);
			RadioGroup genderGroup = (RadioGroup) mView.findViewById(R.id.genderGroup);
			final RadioButton tooBigFontBtn = (RadioButton) mView.findViewById(R.id.ToobigFontBtn);
			final RadioButton bigFontBtn = (RadioButton) mView.findViewById(R.id.bigFontBtn);
			final RadioButton normalFontBtn = (RadioButton) mView.findViewById(R.id.normalFontBtn);
			final RadioButton smallFontBtn = (RadioButton) mView.findViewById(R.id.smallFontBtn);

			int num = Utils.getSettingsparamsByInt(this, "fontsize");

			switch (num) {
			case -1:
				normalFontBtn.setChecked(true);
				break;
			case 1:
				tooBigFontBtn.setChecked(true);
				break;
			case 2:
				bigFontBtn.setChecked(true);
				break;
			case 3:
				normalFontBtn.setChecked(true);
				break;
			case 4:
				smallFontBtn.setChecked(true);
				break;
			default:
				break;
			}

			genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

				
				public void onCheckedChanged(RadioGroup group, int checkedId) {
					if(tooBigFontBtn.getId() == checkedId){
						Utils.setSettingsparamsByInt(BookPagesActivity.this, "fontsize", 1);
					} else if (bigFontBtn.getId() == checkedId) {
						Utils.setSettingsparamsByInt(BookPagesActivity.this, "fontsize", 2);
					} else if (normalFontBtn.getId() == checkedId) {
						Utils.setSettingsparamsByInt(BookPagesActivity.this, "fontsize", 3);
					} else if (smallFontBtn.getId() == checkedId) {
						Utils.setSettingsparamsByInt(BookPagesActivity.this, "fontsize", 4);
					}
				}
			});
			new AlertDialog.Builder(this).setTitle("文字大小设置").setView(mView).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {

				}
			}).show();

			break;

		case R.id.fontStyleBtn:
			int fontColor = Utils.getSettingsparamsByInt(BookPagesActivity.this, "fontColor");
			if (fontColor == -1)
				fontColor = Color.parseColor("black");
			layout.removeAllViews();
			UniversalColorView colorview = new UniversalColorView(this,mColorChangedListener, fontColor);
			layout.addView(bookInfo, params);
			layout.addView(colorview, params);
			
			new AlertDialog.Builder(this).setTitle("文字颜色")
			.setView(layout)
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Utils.setSettingsparamsByInt(BookPagesActivity.this, "fontColor", mColor);
				}
			}).setNeutralButton("恢复默认", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					Utils.setSettingsparamsByInt(BookPagesActivity.this, "fontColor", Color.parseColor("black"));
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					
				}
			}).show();

			break;

		case R.id.backgroundStyleBtn:
			int backgroundColor = Utils.getSettingsparamsByInt(BookPagesActivity.this, "backgroundColor");
			if (backgroundColor == -1)
				backgroundColor = Color.parseColor("#E6D5AB");

			layout.removeAllViews();
			
			UniversalColorView colorview1 = new UniversalColorView(this,mColorChangedListener, backgroundColor);
			layout.addView(bookInfo, params);
			layout.addView(colorview1, params);
			new AlertDialog.Builder(this).setTitle("背景颜色")
			.setView(layout)
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Utils.setSettingsparamsByInt(BookPagesActivity.this, "backgroundColor", mColor);
				}
			}).setNeutralButton("恢复默认", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					Utils.setSettingsparamsByInt(BookPagesActivity.this, "backgroundColor", Color.parseColor("#E6D5AB"));
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					
				}
			}).show();
			
			break;
		case R.id.lightBtn:

			final WindowManager.LayoutParams lp = getWindow().getAttributes();
			float lightf = Utils.getSettingsparamsByFloat(this, "screenLight");
			settingLayout.setDisplayedChild(3);
			int progress = (int) (lightf * 100);
			SeekBar lightSeekBar = (SeekBar) mView.findViewById(R.id.lightseekBar);
			lightSeekBar.setProgress(progress);
			final TextView lightNum = (TextView) mView.findViewById(R.id.lightNum);
			lightNum.setText(progress + "% ");
			lightSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

				
				public void onStopTrackingTouch(SeekBar seekBar) {

				}

				
				public void onStartTrackingTouch(SeekBar seekBar) {

				}

				
				public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
					lightNum.setText(progress + "% ");
					Float tmpFloat = (float) progress / 100;
					System.out.println(tmpFloat);
					lp.screenBrightness = tmpFloat;
					getWindow().setAttributes(lp);
					Utils.setSettingsparamsByFloat(BookPagesActivity.this, "screenLight", tmpFloat);
				}
			});

			new AlertDialog.Builder(this).setTitle("屏幕亮度设置").setView(mView).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {

				}
			}).show();
			break;

		// case R.id.isContinueBtn:
		// settingLayout.setDisplayedChild(0);
		// ToggleButton isContinueBtnTBtn = (ToggleButton)
		// mView.findViewById(R.id.isContinueBtnTBtn);
		// boolean b = Utils.getSettingsparamsByBoolean(this, "isContinue");
		// isContinueBtnTBtn.setChecked(b);
		// isContinueBtnTBtn.setOnCheckedChangeListener(new
		// OnCheckedChangeListener() {
		// 
		// public void onCheckedChanged(CompoundButton buttonView, boolean
		// isChecked) {
		// Utils.setSettingsparamsByBoolean(ReadBookPagesActivity.this,
		// "isContinue", isChecked);
		// }
		// });
		// new
		//AlertDialog.Builder(this).setTitle("继续已读设置").setView(mView).setPositiveButton("确定",
		// new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int whichButton) {
		//
		// }
		// }).show();
		// break;

		}
	}
}
